from fastapi import FastAPI, Request, Header, HTTPException
import uvicorn
import time
from fastapi.responses import JSONResponse

app = FastAPI(
    title="GitHub Webhook webhook",
    description="Receive and handle GitHub webhook request",
    version="1.0.0",
)

@app.middleware("http")
async def log_requests(request: Request, call_next):
    start_time = time.time()

    print(f"=== 收到请求 ===")
    print(f"时间: {time.strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"方法: {request.method}")
    print(f"URL: {request.url}")
    print(f"客户端: {request.client.host}:{request.client.port}")
    print(f"请求头0: {dict(request.headers)}")
    
    # 对于非GET请求，还可以记录请求体（需要小心处理，可能很大）
    if request.method in ["POST", "PUT", "PATCH"]:
        try:
            body = await request.body()
            if body:
                print(f"请求体: {body.decode()}")
        except Exception as e:
            print(f"读取请求体失败: {e}")
    
    # 继续处理请求
    response = await call_next(request)
    
    # 记录响应信息
    process_time = time.time() - start_time
    print(f"响应状态: {response.status_code}")
    print(f"处理时间: {process_time:.3f}秒")
    print(f"=== 请求结束 ===\n")
    
    # 添加处理时间到响应头
    response.headers["X-Process-Time"] = str(process_time)
    return response

@app.get("/")
async def root(request: Request):
    headers = dict(request.headers)
    print(f"请求头1: {headers}")
    return {"status": "online", "message": "GitHub Webhook is running"}

@app.get("/ask")
async def ask(question: str):
    print(f"question: {question}")
    return {"status": "success", "message": "Your question has been received"}

# 监听POST请求的例子
@app.post("/webhook")
async def github_webhook(request: Request):
    # 获取请求头
    headers = dict(request.headers)
    print(f"请求头: {headers}")
    
    # 获取请求体
    body = await request.json()
    
    print(f"收到Webhook请求:")
    print(f"事件类型: {headers.get('x-github-event', 'Unknown')}")
    print(f"请求体: {body}")
    
    return {"status": "success", "message": "Webhook received"}

if __name__ == "__main__":
    uvicorn.run(
        "web:app",
        host="0.0.0.0",
        port=9090,
        reload=False
    )
